package priv.bestbeat.cloud.api.gateway.filters;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpMethod;
import org.springframework.web.server.ServerWebExchange;
import priv.bestbeat.cloud.api.gateway.decoretors.ReusableServerHttpRequest;
import priv.bestbeat.cloud.api.gateway.properties.LoginConstants;
import priv.bestbeat.cloud.common.exceptions.SystemRunningException;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.net.URI;
import java.util.HashMap;

/**
 * 重写请求过滤器（弃用）
 * @author 张渠钦
 * @date 2021/12/30 13:55
 */
@Deprecated
@Slf4j
public class RewriteLoginRequestFilter implements GatewayFilter {

    private static final String DEFAULT_PRINCIPAL_FIELD = "username";

    private static final String DEFAULT_TOKEN_FIELD = "password";

    private final String principalField;

    private final String tokenField;

    private ObjectMapper objectMapper;

    public RewriteLoginRequestFilter() {
        this.principalField = DEFAULT_PRINCIPAL_FIELD;
        this.tokenField = DEFAULT_TOKEN_FIELD;
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ReusableServerHttpRequest httpRequest = new ReusableServerHttpRequest(exchange.getRequest());
        return Mono.from(httpRequest.getBody()).flatMap(dataBuffer -> {
            HashMap<String,Object> m = null;
            try {
                m = this.objectMapper.readValue(dataBuffer.asInputStream(), new TypeReference<HashMap<String,Object>>(){});
            } catch (IOException e) {
                log.error("{}",e.getMessage());
                throw new SystemRunningException(e);
            }
            exchange.getAttributes().put(LoginConstants.LOGIN_PRINCIPAL, m.get(this.principalField));
            exchange.getAttributes().put(LoginConstants.LOGIN_AUTHENTICATION, m.get(this.tokenField));
            return chain.filter(
                    exchange.mutate().request(
                            httpRequest.mutate().method(HttpMethod.GET).uri(URI.create("http://localhost:7001/user/" + m.get(this.principalField))).build()
                    ).build()
            );
        });

    }
}
